<template>

    <div class="bg-container">
        <div class="my-header">
            <div class="search-form" v-if="headerShow">
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="物料编码">
                        <a-select popup-container="html"  :style="{ width: '150px' }" :loading="loading"  @search="handleSearch"
                                  v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                                  @focus="focusSel">
                            <a-option v-for="item in pageData.codeList" :value="item['materialCode']">{{
                                item['materialCode'] ==
                                null ? "" : item['materialCode']
                                }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="物料名称">
                        <a-select popup-container="html"  :style="{ width: '150px' }" :loading="loading" @search="handleSearch"
                                  v-model="pageData.dropDownData1" :filter-option="false" allow-search allow-clear
                                  @focus="focusSel1">
                            <a-option v-for="item in pageData.wlList" :value="item['materialName']">{{
                                item['materialName']
                                }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="规格">
                        <a-select popup-container="html"  :style="{ width: '150px' }" :loading="loading" @search="handleSearch"
                                  v-model="pageData.dropDownData2" :filter-option="false" allow-search allow-clear
                                  @focus="focusSel2">
                            <a-option v-for="item in pageData.ggList" :value="item['spec']">{{ item['spec'] }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="分类">
                        <a-select popup-container="html"  :style="{ width: '150px' }" :loading="loading"  @search="handleSearch"
                                  v-model="pageData.dropDownData3" :filter-option="false" allow-search allow-clear
                                  @focus="focusSel3">
                            <a-option v-for="item in pageData.flList" :value="item['materialClass']">{{
                                item['materialClass']
                                }}
                            </a-option>
                        </a-select>
                    </a-form-item>

                </a-form>
            </div>
              <div class="my-divisders">
            <a-divider orientation="center">
                <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
                   <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
            </a-divider>
             </div>
            <div class="my-tool-bar">
                <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler"
                         @select="selectHandler">
                </Toolbar>
            </div>
        </div>
    </div>

    <div class="gang"></div>

    <div style="padding:10px;box-sizing: border-box;">

        <a-tabs   :lazy-load="true">
            <a-tab-pane title="物料列表">
                <!-- <a-table :style="{
                    height: pageData.rHeight1 + 'px'
                }" size="small" :scrollbar="true" sticky-header @page-change="pagination.change"  stripe :bordered="true" :columns="tableColumns"
                         :row-selection="{ showCheckedAll: true, width: 50, onlyCurrent: true }"
                         v-model:selected-keys="selectedRowKeys" :loading="table.tableLoading" :data="table.dataList"
                         :pagination="{ size: 'small', current: pagination.page, pageSize: pagination.pageSize, total: pagination.total }"
                         :rowKey="rowKey">
                    <template #edit="{ record }">
                        <a-button type="primary" size="small" status="warning" @click="editHandler(record)">
                            <template #icon>
                                <icon-edit/>
                            </template>
                            修 改
                        </a-button>
                    </template>

                </a-table> -->

                  <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"  @grid-ready="gridReady" style="height:100%" :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList" :columnDefs="tc"></AgGridVuesCopys>
            </a-tab-pane>

        </a-tabs>

    </div>
    <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400"
              :visible="pageData.showAdd"
              unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false">
        <template #title>
            {{ pageData.sideTitle }}
        </template>
        <div>
            <a-form ref="formRef" layout="vertical" :model="dataForm">
                <a-form-item label="分类" field="materialClass" :rules="[{ required: true, message: '分类必选' }]"
                             :validate-trigger="['change', 'blur']">
                    <a-select popup-container="html"  placeholder="" v-model="dataForm.materialClass" @change="changeClass">
                        <a-option v-for="item in pageData.getLbAndCk" :value="item['className']">{{ item["className"] }}
                        </a-option>
                    </a-select>
                </a-form-item>

                <a-form-item label="默认仓库" field="warehouseName">
                    <a-input v-model="dataForm.warehouseName" disabled/>
                </a-form-item>
                <a-form-item label="物料编码" field="materialCode"
                             :rules="[{ validator: isChiese }, { required: true, message: '物料编码必填' }]"
                             :validate-trigger="['change', 'blur']">
                    <a-input placeholder="" v-model="dataForm.materialCode"/>
                </a-form-item>
                <a-form-item label="物料名称" field="materialName" :rules="[{ required: true, message: '物料名称必填' }]"
                             :validate-trigger="['change', 'blur']">
                    <a-input placeholder="" v-model="dataForm.materialName"/>
                </a-form-item>
                <a-form-item label="规格" field="spec">
                    <a-input  v-model="dataForm.spec"/>
                </a-form-item>
                <a-form-item label="单位" field="unitNo" >
                    <a-select popup-container="html"  v-model="dataForm.unitNo"
                              @search="searchUnit"  @focus="focusunit" allow-clear allow-search :filter-option="false">
                        <a-option v-for="item in pageData.unitList" :value="item['unit']">{{ item["unit"] }}
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="辅助单位" field="assistUnitNo" >
                    <a-select popup-container="html"   v-model="dataForm.assistUnitNo"
                              @search="searchUnit"  @focus="focusunit" allow-clear allow-search :filter-option="false">
                        <a-option v-for="item in pageData.unitList" :value="item['detailName']">{{ item["detailName"] }}
                        </a-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="价格" field="price">
                    <a-input v-model="dataForm.price"/>
                 </a-form-item>
            </a-form>
            <div>库存选项</div>
            <a-form ref="formRef" layout="inline" :model="dataForm">

                <a-form-item label="批号" field="batchNo">
                    <a-space size="large">
                        <a-input  v-model="dataForm.batchNo"/>
                    </a-space>
                </a-form-item>
                <a-form-item label="安全库存数" field="securityStockNum">
                    <a-space size="large">
                        <a-input  v-model="dataForm.securityStockNum"/>
                    </a-space>
                </a-form-item>
                <a-form-item label="最大库存数" field="maxStockNum">
                    <a-space size="large">

                        <a-input v-model="dataForm.maxStockNum"/>
                    </a-space>
                </a-form-item>
                <a-form-item label="最小库存数" field="minStockNum">
                    <a-space size="large">
                        <a-input v-model="dataForm.minStockNum"/>
                    </a-space>
                </a-form-item>
            </a-form>
        </div>
    </a-drawer>
</template>

<script lang="ts">
    import {post} from '@/api/http'
    import {useTable, useRowKey, useTableColumn, usePagination, useRowSelection} from '@/hooks/table';
    import emitter from "@/hooks/useEventBus";
    import {ref, reactive, onMounted, toRefs} from 'vue'
    import Toolbar from '@/components/Toolbar.vue';
    import {Form, Message, Modal} from '@arco-design/web-vue';
    import {FormInstance} from '@arco-design/web-vue/es/form';
    
    interface MaterialList {
        "id": any,
        "materialCode": any,
        "materialName": string | undefined,
        "spec": string | undefined,
        "materialClass": string | undefined,
        "unitNo": number | undefined,
        "assistNum": number | undefined,
        "assistUnitNo": number | undefined,
        "remark": string | undefined,
        "obsoleteState": number | undefined,
        "deleteState": number | undefined,
        "createName": string | undefined,
        "createTime": string | undefined,
        "updateName": string | undefined,
        "updateTime": string | undefined,
        "warehouseName": any,
        "price": string | undefined,
        "accuracy": string | undefined,
        "batchNo": string | undefined,
        "securityStockNum": number | undefined,
        "maxStockNum": number | undefined,
        "minStockNum": number | undefined,
    }

    export default {
        name: "MaterialList",
        setup() {
            const headerShow = ref<boolean>(true)

            function doRefresh() {
                post({
                    url: "product/Material/getPage",
                    data: {
                        page: pagination.page,
                        size: pagination.pageSize,
                        materialCode: cxbl ,
                        materialName: cxbl1,
                        spec: cxbl2,
                        materialClass: cxbl3,
                        deleteState: "0"
                    },
                })
                    .then(({data, code}: any) => {
                        if (code === 200) {
                            gridOption.value.setRowData(data.list)
                            table.handleSuccess(data.list);
                            pagination.setTotalSize(data.total);
                        }
                    })
                    .catch(console.log);
            }

            const {selectedRowKeys, onSelectionChange} = useRowSelection();
            const pagination = usePagination(doRefresh);
            const table = useTable();
            const rowKey = useRowKey("id");
            const tableColumns = useTableColumn([
                {
                    title: "物料编码",
                    key: "materialCode",
                    dataIndex: "materialCode",
                    width: 150,
                },
                {
                    title: "物料名称",
                    key: "materialName",
                    dataIndex: "materialName",
                    width: 150,
                },
                {
                    title: "默认仓库",
                    key: "warehouseName",
                    dataIndex: "warehouseName",
                    width: 150,
                },
                {
                    title: "价格精度",
                    key: "price",
                    dataIndex: "price",
                    width: 150,
                },
                {
                    title: "规格",
                    key: "spec",
                    dataIndex: "spec",
                    width: 150,
                },
                {
                    title: "分类",
                    key: "materialClass",
                    dataIndex: "materialClass",
                    width: 150,
                },
                {
                    title: "库存单位",
                    key: "unitNo",
                    dataIndex: "unitNo",
                    width: 150,
                },
                {
                    title: "辅助数量",
                    key: "assistNum",
                    dataIndex: "assistNum",
                    width: 150,
                },
                {
                    title: "辅助单位",
                    key: "assistUnitNo",
                    dataIndex: "assistUnitNo",
                    width: 150,

                },
                {
                    title: "创建人",
                    key: "createName",
                    dataIndex: "createName",
                    width: 150,
                },
                {
                    title: "创建时间",
                    key: "createTime",
                    dataIndex: "createTime",
                    width: 150,
                },
                {
                    title: "上传人",
                    key: "updateName",
                    dataIndex: "updateName",
                    width: 150,
                },
                {
                    title: "上传时间",
                    key: "updateTime",
                    dataIndex: "updateTime",
                    width: 150,
                },
                {
                    title: "编辑",
                    key: "edit",
                    dataIndex: "edit",
                    slotName: 'edit',
                    width: 150, fixed: 'right'
                },
            ]);
            const gridOption = ref()
        const gridReady = (params:any) =>{
            gridOption.value = params.api
        }
            const dataForm = reactive<MaterialList>({
                "id": null,
                "materialCode": "",
                "materialName": "",
                "spec": "",
                "materialClass": "",
                "unitNo": 0,
                "assistNum": 0,
                "assistUnitNo": 0,
                "warehouseName": "",
                "price": "",
                "remark": "",
                "obsoleteState": 0,
                "deleteState": 0,
                "createName": "",
                "createTime": "",
                "updateName": "",
                "updateTime": "",
                "accuracy": "",
                "batchNo": "",
                "securityStockNum": 0,
                "maxStockNum": 0,
                "minStockNum": 0
            })
            const pageData = reactive<{

                showAdd: boolean
                sideTitle: string
                codeList: []
                wlList: []
                ggList: []
                flList: []
                dropDownData: any
                dropDownData1: any
                dropDownData2: any
                dropDownData3: any
                getLbAndCk: [],
                unitList: [],
                rHeight1:  number | undefined
            }>({

                showAdd: false,
                sideTitle: '新增物料列表',
                codeList: [],
                wlList: [],
                ggList: [],
                flList: [],
                dropDownData: "",
                dropDownData1: "",
                dropDownData2: "",
                dropDownData3: "",
                getLbAndCk: [],
                unitList: [],
                rHeight1: 0
            });
            const formRef = ref<FormInstance>()
            //下拉框得到焦点
            const focusSel = () => {
                selCxAll({materialCode: ""})
            }
            //下拉框得到焦点
            const focusSel1 = () => {
                selCxAll1({materialName: ""})
            }
            //下拉框得到焦点
            const focusSel2 = () => {
                selCxAll2({spec: ""})
            }
            //下拉框得到焦点
            const focusSel3 = () => {
                selCxAll3({materialClass: ""})
            }
            const focusunit = () => {
                getUnitList(null)
            };

            //下拉数据 物料编码
            const options = ref<any>(pageData.codeList);
            const loading = ref(false);
            const handleSearch = (value: any) => {
                if (value) {
                    const ob = {materialCode: value}
                    loading.value = true;
                    selCxAll(ob);
                    options.value = pageData.codeList;
                    loading.value = false;
                } else {
                    options.value = []
                }
            };

            //下拉框查询 物料编码
            function selCxAll(val: any) {
                post({
                    url: "product/Material/getFieldValue",
                    data: val
                }).then(({data, code}: any) => {
                    if (code === 200) {
                        // (data as string[]).splice(0, 0, "全部");
                        pageData.codeList = data;
                    } else {
                        Message.error({
                            content: "查询失败！",
                            duration: 5000,
                        });
                    }
                });
            }

            //下拉数据 物料名称
            const options1 = ref<any>(pageData.wlList);
            const loading1 = ref(false);
            const handleSearch1 = (value: any) => {
                if (value) {
                    const ob = {materialName: value}
                    loading1.value = true;
                    selCxAll1(ob);
                    options1.value = pageData.wlList;
                    loading1.value = false;
                } else {
                    options1.value = []
                }
            };

            //下拉框查询 物料名称
            function selCxAll1(val: any) {
                post({
                    url: "product/Material/getFieldValue",
                    data: val
                }).then(({data, code}: any) => {
                    if (code === 200) {
                        // (data as string[]).splice(0, 0, "全部");
                        pageData.wlList = data;

                    } else {
                        Message.error({
                            content: "查询失败！",
                            duration: 5000,
                        });
                    }
                });
            }

            //下拉数据 规格
            const options2 = ref<any>(pageData.ggList);
            const loading2 = ref(false);
            const handleSearch2 = (value: any) => {
                if (value) {
                    const ob = {spec: value}
                    loading2.value = true;
                    selCxAll2(ob);
                    options2.value = pageData.ggList;
                    loading2.value = false;
                } else {
                    options2.value = []
                }
            };

            //下拉框查询 规格
            function selCxAll2(val: any) {
                post({
                    url: "product/Material/getFieldValue",
                    data: val
                }).then(({data, code}: any) => {
                    if (code === 200) {
                        // (data as string[]).splice(0, 0, "全部");
                        pageData.ggList = data;

                    } else {
                        Message.error({
                            content: "查询失败！",
                            duration: 5000,
                        });
                    }
                });
            }

            //下拉数据 分类
            const options3 = ref<any>(pageData.flList);
            const loading3 = ref(false);
            const handleSearch3 = (value: any) => {
                if (value) {
                    const ob = {materialClass: value}
                    loading3.value = true;
                    selCxAll3(ob);
                    options3.value = pageData.flList;
                    loading3.value = false;
                } else {
                    options3.value = []
                }
            };

            //下拉框查询 分类
            function selCxAll3(val: any) {
                post({
                    url: "product/Material/getFieldValue",
                    data: val
                }).then(({data, code}: any) => {
                    if (code === 200) {
                        // (data as string[]).splice(0, 0, "全部");
                        pageData.flList = data;

                    } else {
                        Message.error({
                            content: "查询失败！",
                            duration: 5000,
                        });
                    }
                });
            }
            // 单位下拉框
            const searchUnit = (value: any) => {
                if (value) {
                    loading.value = true;
                    getUnitList(value);
                    options.value = pageData.unitList;
                    loading.value = false;
                } else {
                    options.value = []
                }
            };
            // 单位下拉框
            const getUnitList = (val: any) => {
                post({
                    url: 'dict/dictTypeDetail/getListByMap',
                    data: {
                        codeType: 17,
                        detailName: val
                    }
                }).then(({data, code}: any) => {
                    if (code === 200) {
                        pageData.unitList = data;
                    }
                })
            };
            onMounted(() => {
                emitter.on("refresh-MaterialListVue", () => {
                    // doRefresh();
                    selCxAll({materialCode: ""})
                    selCxAll1({materialName: ""})
                    selCxAll2({spec: ""})
                    selCxAll3({materialClass: ""})
                });

                pageData.rHeight1 = document.getElementById("ProductManagement")?.clientHeight
                //表格的高
                if (pageData.rHeight1 !== undefined) {
                    pageData.rHeight1 = pageData.rHeight1 - 250;
                    console.log(pageData.rHeight1);

                }
                window.addEventListener('resize', () => {
                    pageData.rHeight1 = document.getElementById("ProductManagement")?.clientHeight

                    //表格的高
                    if (pageData.rHeight1 !== undefined) {
                        pageData.rHeight1 = pageData.rHeight1 - 250;
                    }

                })
            });
            //查询
            let cxbl = ""
            let cxbl1 = {}
            let cxbl2 = {}
            let cxbl3 = {}
            const selectHandler = () => {
                pagination.page = 1
               cxbl  = pageData.dropDownData
               cxbl1 = pageData.dropDownData1
               cxbl2 = pageData.dropDownData2
               cxbl3 = pageData.dropDownData3
                doRefresh();
            }

            const addHandler = () => {
                for (var key in dataForm) {
                    if (key === "id") {
                        dataForm[key] = null;
                    } else {
                        dataForm[key] = "";
                    }

                }
                getLbAndCk()
                pageData.showAdd = true
                pageData.sideTitle = '新增物料列表'

            }
            //修改 record（本行数据）
            const editHandler = (record: any) => {
                getLbAndCk()
                dataForm.id = record.id;
                dataForm.materialCode = record.materialCode;
                dataForm.materialName = record.materialName;
                dataForm.warehouseName = record.warehouseName;
                dataForm.materialClass = record.materialClass;
                dataForm.spec = record.spec;
                dataForm.price = record.price;
                dataForm.assistNum = record.assistNum;
                dataForm.batchNo = record.batchNo;
                dataForm.maxStockNum = record.maxStockNum;
                dataForm.minStockNum = record.minStockNum;
                dataForm.securityStockNum = record.securityStockNum;
                //侧滑栏滑出滑入
                pageData.showAdd = true
                pageData.sideTitle = '修改物料列表'

            }


            const sideOk = () => {
                formRef.value?.validate().then((err) => {
                    if (pageData.sideTitle === '新增物料列表') {
                        //添加
                        if (!err) {
                            post({
                                url: 'product/Material/insert',
                                data: [dataForm]
                            }).then((res: any) => {

                                if (res.code === 200) {
                                    formRef.value?.resetFields()
                                    pageData.showAdd = false
                                    Message.success({
                                        content: '新增成功',
                                        duration: 5000
                                    })
                                } else {
                                    Message.error({
                                        content: res.message,
                                        duration: 5000
                                    })
                                }
                                doRefresh()
                            })
                        }
                    } else if (pageData.sideTitle === '修改物料列表') {
                        //修改
                        post({
                            url: "product/Material/update",
                            data: [dataForm]
                        }).then(({data, code, message}: any) => {
                            if (code === 200) {
                                formRef.value?.resetFields()
                                Message.success({
                                    content: '修改成功',
                                    duration: 5000
                                })
                                doRefresh()
                                pageData.showAdd = false

                            } else {
                                Message.success({
                                    content: message,
                                    duration: 5000
                                })
                            }
                        });
                    }


                })
            }
            const deleteHandler = () => {
                
                if (gridOption.value.getSelectedRows().length=== 0) {
                return
            }
                Modal.confirm({
                    title: '系统提示',
                    content: '确认删除选中的数据?',
                    onOk() {
                        post({
                            url: 'product/Material/delete',
                            data:gridOption.value.getSelectedRows().map((o:any)=>{return o.id}),
                        }).then(({code, data}: any) => {
                            if (code === 200) {
                                Message.success({
                                    content: '删除成功',
                                    duration: 5000
                                })
                                pagination.page = 1
                                doRefresh()
                            } else {
                                Message.error({
                                    content: '删除失败',
                                    duration: 5000
                                })
                            }

                        })
                    }
                })
            }
            //查询 类别带出仓库
            const getLbAndCk = () => {
                post({
                    url: 'product/MaterialClass/getList',
                    data: {"deleteState": 0}
                }).then(({code, data}: any) => {
                    if (code === 200) {
                        pageData.getLbAndCk = data;

                    } else {
                        Message.error({
                            content: '查询失败',
                            duration: 5000
                        })
                    }

                })
            }

            //下拉框改变事件
            const changeClass = (val: any) => {
                pageData.getLbAndCk.forEach(function (o: any) {
                    if (o["className"] == val) {
                        dataForm.warehouseName = o["warehouseName"]
                    }
                })
            }
            //判断是否填写了中文
            const isChiese = (value: string, cb: Function) => {
                return new Promise<void>(resolve => {
                    if (window.encodeURI(value).indexOf('%') !== -1) {
                        cb('填写的值只能是英文数字组合或英文，数字！')
                    }
                    resolve()
                })

            }
            //input离开焦点 将小写转大写
            const inputBlur = () => {
                dataForm.materialCode = dataForm.materialCode.toUpperCase();
            }
            let tc:any[] = tableColumns.map((o:any)=>{

let obj = {
    headerName:o.title,
    field:o.key,
    pinned:o['fixed']
}
if(o.slotName === 'action'){
    obj['resizable'] = false
    obj['filter'] = false
    obj['sortable'] = false
    obj["lockPosition"]="right"

    obj['cellRenderer'] = {
        template:`<a-tag class="tagCss" @click="a">修改</a-tag>`,
        setup(props:any){
            const a = () =>{
                editHandler(props.params.data)
            }
            return {
                a
            }
        }
        
    }
}

return obj
})

let a = [{
showRowGroup: 'hide_def',
"headerName": "",
"checkboxSelection": true,
"headerCheckboxSelection": true,
"pinned": "left",
"width": 50,
resizable: false,
filter:false,
sortable:false,
minWidth: 50,
maxWidth: 50,
lockPosition:"left",
}]
tc = a.concat(tc)
        const defaultColDef = {
            sortable: true,
            resizable:true,
            filter: true,
            // flex: 1
          }
            return {
                defaultColDef,
                tc,
                deleteHandler,
                sideOk,
                formRef,
                dataForm,
                addHandler,
                selectedRowKeys,
                pagination,
                tableColumns,
                table,
                rowKey,
                pageData,
                editHandler,
                selectHandler,
                options,
                loading,
                handleSearch,
                options1,
                loading1,
                handleSearch1,
                options2,
                loading2,
                handleSearch2,
                options3,
                loading3,
                handleSearch3,
                getLbAndCk,
                getUnitList,
                changeClass,
                focusSel,
                focusSel1,
                focusSel2,
                focusSel3,
                inputBlur,
                isChiese,
                searchUnit,
                focusunit,
                headerShow,
                gridReady
            };
        },
        components: {Toolbar, }
    }
</script>
<style scoped lang="less">




    .toolbar-item {
        cursor: pointer;
    }
</style>